package cn.hchaojie.camp.week2.qa.scorechart;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtils {
	private static final int SCORE = 0; // 分数列
	private static final int COURSE = 1; // 课程列
	private static final int NAME = 2; // 姓名列
	
	public static Map<String, List<StudentScore>> parseFile(String file) {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "gbk"));) {

			String line = br.readLine(); // 跳过第一行

			List<StudentScore> scores = new ArrayList<>();

			// 读取每一行，封装到StudentScore里面
			while ((line = br.readLine()) != null) {
				scores.add(parseLine(line));
			}

			// 将不同课程的分数分组放入map
			Map<String, List<StudentScore>> courseScores = new HashMap<>();

			// 遍历所有的分数
			for (StudentScore s : scores) {
				String course = s.getCourse();
				// 把线性代数的放到一起
				if (courseScores.containsKey(course)) {
					List<StudentScore> list = courseScores.get(course);
					list.add(s);
				} else {	// 把高等数学的放到一起
					List<StudentScore> list = new ArrayList<>();
					list.add(s);
					courseScores.put(course, list);
				}
			}

			return courseScores;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static StudentScore parseLine(String line) {
		// csv文件以逗号分割
		String[] parts = line.split(",");

		return new StudentScore(parts[SCORE], parts[COURSE], parts[NAME]);
	}
}
